package org.litespring.beans.factory.support;

import org.litespring.beans.factory.config.SingletonBeanRegistry;
import org.litespring.util.Assert;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ChangLiang
 * @date 2020/7/22
 */
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    /** Cache of singleton objects: bean name to bean instance. */
    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(64);

    @Override
    public void registerSingleton(String beanId, Object singletonObject) {
        Assert.notNull(beanId, " 'beanName' must not be null");

        Object oldObject = this.singletonObjects.get(beanId);
        if (oldObject != null) {
            throw new IllegalStateException("Could not register object [" + singletonObject +
                    "] under bean name'" + beanId + "': there is already object [" + oldObject + "]");
        }
        this.singletonObjects.put(beanId, singletonObject);
    }

    @Override
    public Object getSingleton(String beanId) {
        return this.singletonObjects.get(beanId);
    }
}
